package cn.intotw.rdcj.core.bean;

import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.ExtendedModelMap;


/**
 *
 */
public class DataResponse<T> extends ExtendedModelMap {
    public static final String ERRCODE_SUCCESS = "0000";//处理成功
    public static final String ERRMSG_SUCCESS = "成功";



    public static <T> DataResponse<T> failure(String errcode, String errmsg) {
        return new DataResponse<T>(errcode, errmsg);
    }

    public static <T> DataResponse<T> success() {
        return new DataResponse<T>(ERRCODE_SUCCESS, ERRMSG_SUCCESS);
    }

    public static <T> DataResponse<T> success(String name, T data) {
        DataResponse<T> serviceResponse = success();
        if (StringUtils.isEmpty(name)) {
            serviceResponse.addAttribute(data);
        } else {
            serviceResponse.addAttribute(name, data);
        }
        return serviceResponse;
    }

    public static <T> DataResponse<T> success(T data) {
        return success(null, data);
    }

    public static <T> DataResponse<T> successWithResult(T data) {
        return success("result", data);
    }

    private DataResponse(String errcode, String errmsg) {
        addAttribute("errcode", errcode);
        addAttribute("errmsg", errmsg);
        addAttribute("success", isSuccess());
    }

    public boolean isSuccess() {
        return StringUtils.equals((String) get("errcode"), ERRCODE_SUCCESS);
    }

    public String getMessage() {
        return (String) get("errmsg");
    }

    public <T> T getAttribute(String name) {
        return (T) get(name);
    }

    @Override
    public String toString() {
        return "DataResponse" + super.toString();
    }
}

